import {
  overviewControllerGetAllStationMapDatas,
  overviewControllerGetLevelStationCount,
} from '@/services/ess/mainpageOverview';
import { useIntl } from '@umijs/max';
import * as echarts from 'echarts';
import pinyin from 'pinyin';
import { useEffect, useRef, useState } from 'react';
import { chainaGeoJson } from '../utils/chinajson';
import { chinaMapConfig } from '../utils/chinaMapConfig';
import { provinceMapConfig } from '../utils/provinceMapConfig';
import { formatPower } from '../utils/tools';
import { fetchStationLocation } from '../utils/useFetchStationData';
import { worldMapConfig } from '../utils/worldMapConfig';
import { geoJson } from '../utils/worldZH';
import Styles from './StationDataMap.less';

export interface TooltipData {
  name: string;
  stationName: string;
  online: boolean;
  date: string;
  tenant: string;
  capacity: string;
  power: string;
  efficiency: string;
  loop: string;
  all: string;
  charge: string;
  discharge: string;
}

interface MapChartProps {
  toolTipData: TooltipData[];
}

// 声明 StationTooltipData 类型
interface StationTooltipData {
  name: string;
  stationName: string;
  online: boolean;
  date: string;
  tenant: string;
  capacity: string;
  power: string;
  efficiency: string;
  loop: string;
  all: string;
  charge: string;
  discharge: string;
}

export default function MapChart({ toolTipData }: MapChartProps) {
  const ref = useRef<HTMLDivElement | null>(null);
  const [isWorldMap, setIsWorldMap] = useState(true);
  const [currentProvince, setCurrentProvince] = useState('');
  const [provinceTooltipData, setProvinceTooltipData] = useState<StationTooltipData[]>([]);
  const [chinaCount, setChinaCount] = useState<number | null>(null);
  const mapInstanceRef = useRef<echarts.ECharts | null>(null);
  const lastParamsRef = useRef<any>(null);
  const intl = useIntl();
  const isEnglish = intl.locale === 'en-US';
  const fetchStationMap = async (province: string): Promise<StationTooltipData[]> => {
    const mapDataResponse = await overviewControllerGetAllStationMapDatas({
      parent: province,
      level: 'city',
    });
    if (mapDataResponse.success && mapDataResponse.data) {
      const data = mapDataResponse.data ?? [];
      const tipData = data.map((station: any) => {
        const formattedCapacity = formatPower(station.capacity, false);
        const formattedPower = formatPower(station.ratedPower, true);
        const formattedDischargedEnergy = formatPower(station.dischargedEnergy, false);
        const formattedChargedEnergy = formatPower(station.chargedEnergy, false);

        return {
          name: station.address,
          address: station.address,
          stationName: station.stationName,
          online: station.online ?? false,
          date: station.startRunTime ?? '--',
          tenant: station.tenantName ?? '--',
          capacity: formattedCapacity.value + (station.capacityUnit ?? formattedCapacity.unit),
          power: formattedPower.value + (station.ratedPowerUnit ?? formattedPower.unit),
          efficiency:
            station.conversion !== null && station.conversion !== undefined
              ? station.conversion + '%'
              : '--',
          loop:
            station.loopCount !== null && station.loopCount !== undefined
              ? station.loopCount + `&nbsp;${intl.formatMessage({ id: 'bigdata.times' })}`
              : '--',
          all:
            station.efficiency !== null && station.efficiency !== undefined
              ? station.efficiency + '%'
              : '--',
          charge:
            formattedChargedEnergy.value +
            (station.chargedEnergyUnit ?? formattedChargedEnergy.unit),
          discharge:
            formattedDischargedEnergy.value +
            (station.dischargedEnergyUnit ?? formattedDischargedEnergy.unit),
        };
      });

      return tipData;
    }
    return [];
  };

  const renderMap = async () => {
    const mapInstance = echarts.getInstanceByDom(ref.current!) || echarts.init(ref.current!);
    mapInstanceRef.current = mapInstance;

    let chinaStationCount: { name: string; value: number }[] = [];
    let offline: number;
    let online: number;
    let chinaStationBumber: number;
    async function fetchAndTransformData() {
      try {
        // 调用接口获取数据
        const response = await overviewControllerGetLevelStationCount({
          parent: '中国',
          level: 'province',
        });
        // @ts-ignore
        online = response.data.online;
        // @ts-ignore
        offline = response.data.offline;
        chinaStationBumber = online + offline;
        // 检查 response.data 是否为数组
        // @ts-ignore
        if (Array.isArray(response.data.datas)) {
          //@ts-ignore
          response.data.datas.forEach((item) => {
            const { name, count } = item;
            // 移除名称中的 "省" 和 "自治区"
            // @ts-ignore
            let cleanedName = name.replace('省', '').replace('自治区', '');
            // 保留特定省份 "黑龙江" 和 "内蒙古" 的前三个字符，其他省份保留前两个字符
            if (cleanedName === '黑龙江' || cleanedName === '内蒙古') {
              cleanedName = cleanedName.slice(0, 3);
            } else {
              cleanedName = cleanedName.slice(0, 2);
            }
            // 创建新的对象并推送到 chinaStationCount 数组中
            // @ts-ignore
            chinaStationCount.push({ name: cleanedName, value: count });
          });
        } else {
          console.error('返回的数据不是一个数组:', response.data);
        }
      } catch (error) {
        console.error('获取数据时发生错误:', error);
      }
    }

    await fetchAndTransformData(); // 等待数据获取完成
    const stationData = await fetchStationLocation();
    // 统计中国站点总数
    let localChinaCount: number = 0;
    // stationData.forEach((item: any) => {
    //   const geoCoord = chinaStationGeoCoordMap[item.name];
    //   if (geoCoord && isInChina(geoCoord[0], geoCoord[1])) {
    //     localChinaCount++;
    //   }
    // });
    stationData.forEach((item: any) => {
      if (/[\u4e00-\u9fa5]/.test(item.stationAddress)) {
        localChinaCount++;
      }
    });
    // 更新 chinaCount 状态
    setChinaCount(localChinaCount);
    // 只有当 localChinaCount 大于 0 时才渲染地图
    if (localChinaCount >= 0) {
      let option;
      if (isWorldMap) {
        option = await worldMapConfig({
          min: 0,
          toolTipData,
          // @ts-ignore
          chinaCount: chinaStationBumber,
          intl,
        });
      } else if (currentProvince) {
        option = await provinceMapConfig({
          provinceName: currentProvince,
          toolTipData: provinceTooltipData,
          intl: intl,
        });
      } else {
        // @ts-ignore
        option = await chinaMapConfig({
          min: 0,
          chinaStationCount,
          toolTipData,
          online,
          offline,
          intl: intl,
        });
      }
      mapInstance.setOption(option);

      mapInstance.off('click');
      // @ts-ignore
      mapInstance.on('click', async (params) => {
        if (isWorldMap && params.name === '中国') {
          setIsWorldMap(false);
          // 清除世界地图渲染相关的数据
          mapInstance.clear();
        } else if (!isWorldMap && !currentProvince) {
          // 动态导入省份地图数据
          const getProvincePinyin = (provinceName: string) => {
            switch (provinceName) {
              case '陕西':
                return 'shanxi1';
              case '山西':
                return 'shanxi';
              case '西藏':
                return 'xizang';
              case '重庆':
                return 'chongqing';
              default:
                return pinyin(provinceName, { style: pinyin.STYLE_NORMAL }).join('');
            }
          };

          const provincePinyin = getProvincePinyin(params.name);

          const provinceJson = await import(`../utils/province/${provincePinyin}.json`)
            .then((module) => module.default)
            .catch((error) => {
              console.error(`Error importing JSON for province ${params.name}:`, error);
              return null;
            });
          echarts.registerMap(provincePinyin, provinceJson);

          // 获取省份电站数据
          const tooltipData = await fetchStationMap(params.name); // 这里使用中文字符
          console.log('params.name', params.name, tooltipData);
          setProvinceTooltipData(tooltipData);
          setCurrentProvince(provincePinyin);
          mapInstance.clear();
          renderMap();
        }
      });
    }
  };

  const handleBackButtonClick = () => {
    if (currentProvince) {
      setCurrentProvince('');
    } else if (!isWorldMap) {
      setIsWorldMap(true);
    }
    mapInstanceRef.current?.clear();
  };

  useEffect(() => {
    // 当 currentProvince 或 isWorldMap 改变时重新渲染地图
    if (chinaCount !== null && chinaCount >= 0) {
      renderMap();
    }
  }, [currentProvince, isWorldMap, provinceTooltipData, chinaCount]);

  const syncZoomAndMove = () => {
    if (mapInstanceRef.current && lastParamsRef.current) {
      const { zoom } = lastParamsRef.current;
      mapInstanceRef.current.dispatchAction({
        type: 'georoam',
        groupId: 'worldMapGroup',
        zoom: zoom,
        center: undefined,
      });
    }
  };

  useEffect(() => {
    const mapInstance = echarts.getInstanceByDom(ref.current!) as echarts.ECharts | null;
    mapInstanceRef.current = mapInstance;

    if (mapInstance) {
      const handleGeoRoam = (params: any) => {
        const { componentType, type, zoom, center } = params;
        if (componentType === 'geo' && type === 'georoam') {
          lastParamsRef.current = { zoom, center };
          requestAnimationFrame(syncZoomAndMove);
        }
      };

      mapInstance.on('georoam', handleGeoRoam);

      return () => {
        mapInstance.off('georoam', handleGeoRoam);
      };
    }
  }, []);

  useEffect(() => {
    const fixGeoJson = (geoJson: any) => {
      if (geoJson.type !== 'FeatureCollection') {
        geoJson.type = 'FeatureCollection';
      }
      return geoJson;
    };
    echarts.registerMap('world', fixGeoJson(geoJson));
    echarts.registerMap('china', fixGeoJson(chainaGeoJson));
    renderMap();
  }, [toolTipData, isWorldMap, currentProvince]);

  useEffect(() => {
    window.onresize = function () {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      mapInstanceRef.current && mapInstanceRef.current.resize();
    };
    return () => {
      // eslint-disable-next-line @typescript-eslint/no-unused-expressions
      mapInstanceRef.current && mapInstanceRef.current.dispose();
    };
  }, []);

  return (
    <div className={Styles.mapBg}>
      <div
        id="chart"
        className={Styles.dataMap}
        style={{ width: '100%', height: '55vh' }}
        ref={ref}
      ></div>
      {(!isWorldMap || currentProvince) && (
        // eslint-disable-next-line react/button-has-type
        <button
          className={`${Styles.backButton} ${isEnglish ? Styles.backButtonEn : ''}`}
          onClick={handleBackButtonClick}
        ></button>
      )}
    </div>
  );
}
